// components/DropZone.tsx
import React, { useEffect } from 'react'
import { dragBus } from '../utils/dragBus'
import type { BodyItem } from '../types'

interface Props {
  body: BodyItem[]
  onInsert: (index: number, item: BodyItem) => void // 插入真实节点
  onPlaceholder: (index: number | null) => void // 更新占位索引
  onMove?: (fromIndex: number, toIndex: number) => void // 移动现有节点
}

export const DropZone: React.FC<Props> = ({ body, onInsert, onPlaceholder, onMove }) => {
  useEffect(() => {
    const zone = document.getElementById('phone-inner')
    if (!zone) return

    let hoverIndex: number | null = null

    const overHandler = (e: DragEvent) => {
      e.preventDefault()
      const y = e.clientY
      const rects = Array.from(zone.querySelectorAll<HTMLElement>('[data-index]'))
      
      // 计算应该插入的位置
      let idx = rects.length // 默认放到末尾
      for (let i = 0; i < rects.length; i++) {
        const node = rects[i]
        const rect = node.getBoundingClientRect()
        // 如果鼠标在元素的上半部分，则在这个元素前插入
        if (y < rect.top + rect.height / 2) {
          idx = i
          break
        }
      }
      
      // 只有当索引真正改变时才更新
      if (hoverIndex !== idx) {
        hoverIndex = idx
        onPlaceholder(idx) // 通知父组件渲染占位
      }
    }

    const dropHandler = (e: DragEvent) => {
      e.preventDefault()
      if (dragBus.payload && hoverIndex !== null) {
        // 检查是否是移动现有组件
        const payload = dragBus.payload;
        const sourceIndex = payload._index as number | undefined;
        
        if (sourceIndex !== undefined && onMove) {
          // 移动现有组件
          onMove(sourceIndex, hoverIndex);
        } else {
          // 从工具栏添加新组件
          let newItem: BodyItem;
          
          switch (payload.type) {
            case 'search':
              newItem = {
                id: Date.now(),
                type: 'search',
                placeholder: '请输入搜索内容',
              } as BodyItem;
              break;
              
            case 'notice':
              newItem = {
                id: Date.now(),
                type: 'notice',
                title: '公告标题',
                content: '这是公告内容',
              } as BodyItem;
              break;
              
            default:
              // 默认创建一个基础组件
              newItem = {
                id: Date.now(),
                type: payload.type as string,
              } as BodyItem;
          }
          
          onInsert(hoverIndex, newItem);
        }
      }
      onPlaceholder(null)
      dragBus.reset()
    }

    const leaveHandler = () => onPlaceholder(null)

    zone.addEventListener('dragover', overHandler)
    zone.addEventListener('drop', dropHandler)
    zone.addEventListener('dragleave', leaveHandler)

    return () => {
      zone.removeEventListener('dragover', overHandler)
      zone.removeEventListener('drop', dropHandler)
      zone.removeEventListener('dragleave', leaveHandler)
    }
  }, [body, onInsert, onPlaceholder, onMove])

  return null // 本组件只负责事件，不渲染任何 DOM
}